package com.aididi.demospringbootrabbitmqcallback.task;

import com.aididi.demospringbootrabbitmqcallback.Producer.OrderSender;
import com.aididi.demospringbootrabbitmqcallback.constant.Constants;
import com.aididi.demospringbootrabbitmqcallback.dao.BrokerMessageLogMapper;
import com.aididi.demospringbootrabbitmqcallback.entity.BrokerMessageLogVO;
import com.aididi.demospringbootrabbitmqcallback.entity.Order;
import com.aididi.demospringbootrabbitmqcallback.util.JsonUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Auther: xuzexiang
 * @Date: 2018-11-18 0018 23:51
 * @Description:    定时任务自动重试
 */
@Component
@Log4j2
public class RetryMessageTask {

    private final BrokerMessageLogMapper brokerMessageLogMapper;
    private final OrderSender orderSender;
    @Autowired
    public RetryMessageTask(BrokerMessageLogMapper brokerMessageLogMapper,OrderSender orderSender) {
        this.brokerMessageLogMapper = brokerMessageLogMapper;
        this.orderSender = orderSender;
    }

    /**
     * 定时任务抓取失败的订单 进行重试
     *  启动完成3秒后开始执行，每隔10秒执行一次
     */
    @Scheduled(initialDelay = 3000,fixedDelay = 10000)
    public void task(){
        log.debug("开启重发消息定时任务");
        List<BrokerMessageLogVO> messageLogList = this.brokerMessageLogMapper.listSendFailureAndTimeoutMessage();
        /*messageLogList.stream().filter(messageLog -> messageLog.getTryCount()>= Constants.MAX_RETRY_COUNT).forEach(
                xx -> {
                    xx.setMessage(xx.getMessage());
                    xx.setStatus(Constants.OrderSendStatus.SEND_FAILURE);
                    this.brokerMessageLogMapper.changeBrokerMessageLogStatus(xx);
                });*/
        messageLogList.forEach(messageLog -> {
            log.debug("处理消息日志：{}",messageLog);
            if(messageLog.getTryCount()>=Constants.MAX_RETRY_COUNT){
                BrokerMessageLogVO brokerMessageLogVO  =new BrokerMessageLogVO();
                brokerMessageLogVO.setMessageId(messageLog.getMessageId());
                brokerMessageLogVO.setStatus(Constants.OrderSendStatus.SEND_FAILURE);
                brokerMessageLogMapper.changeBrokerMessageLogStatus(brokerMessageLogVO);
            }else {
                brokerMessageLogMapper.updateRetryCount(messageLog);
                Order order =JsonUtil.covertJsonToObject(messageLog.getMessage(),Order.class);
                try {
                    orderSender.send(order);
                } catch (Exception e) {
                    log.error("消息发送异常：{}",e);
                }
            }
        });
        log.debug("重发消息定时任务结束");

    }

}
